//
//  HBMyRedPacketListCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/7.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBMyRedPacketListCtrl.h"
#import "HBMyRedPacketListCell.h"

#import "HBGetUserRedRecordInfo.h"
#import "HBGetUserRedRecordItemInfo.h"
#import "HBGetUserRedRecordParam.h"
#import "HBGetUserRedRecordParser.h"

#import "MJRefresh.h"
#import "HBShakeGamesCtrl.h"

@interface HBMyRedPacketListCtrl ()
<UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic) int pageNum;
@property (nonatomic, strong) HBGetUserRedRecordInfo *recordInfo;

@property (nonatomic, strong) UIImageView *emptyIV;
@property (nonatomic, strong) UIButton *emptyBtn;

@end

//My_RedPacket
@implementation HBMyRedPacketListCtrl

#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
   
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"红包";
    self.pageNum = 1;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_tableView];
    INIT_TABLE(_tableView);
    
    __weak UITableView *tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        [weakSelf hideEmptyIV];
        weakSelf.pageNum = 1;
        [weakSelf requestToGetRedList];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            [tableView.mj_header endRefreshing];
//        });
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            [tableView.mj_footer endRefreshing];
//        });
        
        if (weakSelf.recordInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestToGetRedList];
        }
        else
        {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        // 结束刷新
                        [tableView.mj_footer endRefreshing];
                    });
        }
        
    }];
    
//    [self.tableView.mj_header beginRefreshing];
    
    self.pageNum = 1;
    [self requestToGetRedList];
    
}

#pragma mark - private

- (UIButton *)createButtonWithFrame:(CGRect)frame normalBackgroundColor:(UIColor *)normalBGColor disabledBackgroundColor:(UIColor *)disabledBGColor higlightedBackgroundColor:(UIColor *)higlightedBGColor  normalFontColor:(UIColor *)normalFontColor higlightedFontColor:(UIColor *)higlightedFontColor disabledFontColor:(UIColor *)disabledFontColor title:(NSString *)title contentHorizontalAlignment:(UIControlContentHorizontalAlignment)textAlignment font:(UIFont *)font superView:(UIView *)superView
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundColor:normalBGColor];
    [button setBackgroundColor:normalBGColor forState:UIControlStateNormal];
    [button setBackgroundColor:disabledBGColor forState:UIControlStateDisabled];
    [button setBackgroundColor:higlightedBGColor forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:normalFontColor forState:UIControlStateNormal];
    [button setTitleColor:disabledFontColor forState:UIControlStateDisabled];
    [button setTitleColor:higlightedFontColor forState:UIControlStateHighlighted];
    button.titleLabel.font = font;
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setContentHorizontalAlignment:textAlignment];
    [superView addSubview:button];
    button.enabled = NO;
    [button.layer setCornerRadius:4.0f];
    button.layer.masksToBounds = YES;
    return button;
}


- (void)showEmptyIV
{
//    self.emptyIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"My_Red_Empty"]];
//    self.emptyIV.center = self.tableView.center;
//    self.emptyIV.center = CGPointMake(self.emptyIV.center.x, self.emptyIV.center.y-32);
//    [self.view addSubview:self.emptyIV];
//    
//    self.emptyBtn = [self createButtonWithFrame:CGRectMake(15, self.emptyIV.y+self.emptyIV.height+57, SCREEN_WIDTH-30, 44) normalBackgroundColor:[LCCommon getColor:@"f24545"] disabledBackgroundColor:[LCCommon getColor:@"bd3737"] higlightedBackgroundColor:[LCCommon getColor:@"f24545"] normalFontColor:[LCCommon getColor:@"ffffff"] higlightedFontColor:[LCCommon getColor:@"ffffff"] disabledFontColor:[LCCommon getColor:@"fd7a7a"] title:@"现在就去抢红包" contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter font:[UIFont systemFontOfSize:18] superView:self.view];
//    self.emptyBtn.enabled = YES;
    
    self.emptyIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"My_Red_Empty"]];
    self.emptyIV.center = self.tableView.center;
    self.emptyIV.center = CGPointMake(self.emptyIV.center.x, self.emptyIV.center.y-32);
    [self.view addSubview:self.emptyIV];
}

- (void)hideEmptyIV
{
    [self.emptyIV removeFromSuperview];
    self.emptyIV = nil;
//    [self.emptyBtn removeFromSuperview];
//    self.emptyBtn = nil;
}


- (void)uploadRedPacketListCell:(HBMyRedPacketListCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    /*
     @property (nonatomic, strong) UILabel *titleLable;
     @property (nonatomic, strong) UILabel *fromLable;
     @property (nonatomic, strong) UILabel *timeLable;
     @property (nonatomic, strong) UILabel *statusLable;
     @property (nonatomic, strong) UILabel *rateLable;
     */
    HBGetUserRedRecordItemInfo *itemInfo = self.recordInfo.dataAry[indexPath.row];
    cell.titleLable.text = itemInfo.redName;
    cell.fromLable.text = itemInfo.redSource;
    cell.timeLable.text = itemInfo.effectDate;
    cell.statusLable.text = itemInfo.redStatus;
    //+0.5%格式是否正确，注意格式的转化
    cell.rateLable.text = [NSString stringWithFormat:@"+%.2f%%",(int)([itemInfo.redRate floatValue]*10000)/100.0];
    
}

#pragma mark - active

- (void)clickButton:(UIButton *)sender
{
    [self.navigationController pushViewController:[[HBShakeGamesCtrl alloc]initWithNibName:NSStringFromClass([HBShakeGamesCtrl class]) bundle:nil] animated:YES];
}

#pragma mark - delegate&datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.recordInfo.dataAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = NSStringFromClass([HBMyRedPacketListCell class]);;
    
    HBMyRedPacketListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell)
    {
        cell = [[HBMyRedPacketListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [self uploadRedPacketListCell:(HBMyRedPacketListCell *)cell atIndexPath:indexPath];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1/[UIScreen mainScreen].scale;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/[UIScreen mainScreen].scale)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return Height_HBMyRedPacketListCell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark - net

- (void)requestToGetBankList
{
    //    [CustomLoadingView showHudToView:self.view];
    //    HBGetBankListParam *param = [[HBGetBankListParam alloc]init];
    //    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    //    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    //    HBGetBankListParser *parser = [[HBGetBankListParser alloc]init];
    //    [NetCenter getDataFromURL:Method_getBankList params:param parser:parser result:^(ParserResult *myResult) {
    //        [CustomLoadingView hideHudForView:self.view];
    //        if (myResult.code==0)
    //        {
    //            HBGetBankListInfo *listInfo = (HBGetBankListInfo *)myResult.result;
    //            self.bankListInfo = listInfo;
    //            [self.tableView reloadData];
    //        }
    //        else
    //        {
    //            DISSMISS_ERR(myResult.message);
    //        }
    //
    //    } failure:^(NSError *error) {
    //        [CustomLoadingView hideHudForView:self.view];
    //        DISSMISS_ERR([error description]);
    //    }];
}


- (void)requestToGetRedList
{
    [CustomLoadingView showHudToView:self.view];
    HBGetUserRedRecordParam *param = [[HBGetUserRedRecordParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.pageNum = [NSString stringWithFormat:@"%d",self.pageNum];
    
    HBGetUserRedRecordParser *parser = [[HBGetUserRedRecordParser alloc]init];
    [NetCenter getDataFromURL:Method_getUserRedRecord params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (self.pageNum==1)
        {
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
        }
        if (myResult.code==0)
        {
            HBGetUserRedRecordInfo *urlInfo = (HBGetUserRedRecordInfo *)myResult.result;
            if (self.pageNum==1)
            {
                self.recordInfo = urlInfo;
                [self.tableView reloadData];
                if (self.recordInfo.dataAry.count==0)
                {
                    [self showEmptyIV];
                }
            }
            else
            {
                if (urlInfo.dataAry.count>0)
                {
                    NSMutableArray *array = [NSMutableArray arrayWithArray:self.recordInfo.dataAry];
                    [array addObjectsFromArray:urlInfo.dataAry];
                    self.recordInfo.dataAry = array;
                    [self.tableView reloadData];
                }
                else
                {
                    self.pageNum--;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
        
        }
        else
        {
            DISSMISS_ERR(myResult.message);
            if (self.pageNum>1)
            {
                self.pageNum--;
            }
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
        
        if (self.pageNum==1)
        {
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
            self.pageNum--;
        }
        
    }];
}




@end
